<template>
  <view class="tn-shop-submit-order">
    <tn-custom bg-custom-color="#f1eef3" is-back="true">
      <block slot="backText">返回</block>
      <block slot="content">提交订单</block>
    </tn-custom>

    <view class="cu-card case address">
      <view class="cu-item shadow bg-red">
        <view class="cu-list menu text-black">
          <view class="cu-item list">
            <view class="">
              <text class="">收货人</text>
            </view>
            <view class="">
              <view class="">{{ orderData.address.user_name }}</view>
            </view>
          </view>
          <view class="cu-item list">
            <view class="">
              <text class="">联系方式</text>
            </view>
            <view class="">
              <view class="">{{ orderData.address.tel_number }}</view>
            </view>
          </view>
          <view class="cu-item list">
            <view style="width: 200rpx;">
              <text class="">收货地址</text>
            </view>
            <view class="">
              <view class="tn-align">
                {{ orderData.address.province_name + ' ' +
                   orderData.address.city_name + ' ' +
                   orderData.address.county_name + ' ' +
                   orderData.address.detail_info
                }}
              </view>
            </view>
          </view>
        </view>
        <button class="cu-btn bg-white text-olive get-address" @click="chooseUserAddress">获取收货地址</button>
      </view>
    </view>

    <view class="cu-card case">
      <view class="cu-item" style="margin-top: 0px;">
        <view class="cu-card case order-product">
          <view v-for="(product_item, product_index) in orderProductData" :key="product_index" class="cu-item shadow bg-red list">
            <view class="image">
              <image :src="product_item.image" mode="aspectFill"></image>
              <view class="product-information bg-shadeBottom">
                <view class="text-cut title">{{ product_item.title }}</view>
                <view class="property">
                  <text>
                    <block v-for="(property_item, property_index) in product_item.property" :key="property_index">
                      {{ property_index > 0 ? ';' : ''}}{{ property_item }}
                    </block>
                  </text>
                </view>
              </view>
            </view>
            <view class="flex padding justify-between align-center">
              <view class="text-gray">￥{{ product_item.price }}</view>
              <view class="margin-left text-gray text-lg">x{{ product_item.count }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="cu-list menu margin-bottom order-information">
      <view class="cu-item list shipping">
        <view class="cu-form-group">
          <view class="title">配送方式</view>
          <picker @change="shippingChange" :value="shippingPickerIndex" :range="shippingPicker">
            <view class="picker">
              {{ shippingPicker[shippingPickerIndex] }}
            </view>
          </picker>
        </view>
      </view>
      <view class="cu-form-group align-start">
        <view class="title">订单备注</view>
        <textarea maxlength="255" v-model="orderData.notes" placeholder="输入订单备注"></textarea>
      </view>
    </view>

    <view class="cu-tabbar-height"></view>

    <view class="cu-bar bg-white tabbar shop tn-footerfixed">
      <view class="action"></view>
      <view class="padding-right">
        <text class="padding-right-xs text-gray">
          共{{ orderProductData.length }}件
        </text>
        <text class="padding-right-xs">
          合计: <text class="text-red">¥ {{ orderSumPrice }}</text>
        </text>
        <button class="cu-btn bg-red round shadow-blur" @click="submitOrder">提交订单</button>
      </view>
    </view>

    <tn-wx-login :show="showLogin" desc="用户记录您的登录信息" @closeLoginModal="closeLoginModal" @getUserInfo="getUserInfo"></tn-wx-login>
  </view>
</template>

<script>
  import {
    checkUserScope,
    getUserInfo
  } from '@/utils/user.js'
  import {
    getSubmitOrderProductFromCache,
    addSubmitOrderProductToCache,
    getShoppingCartDataFromCache,
    updateShoppingCartDataToCache
  } from '@/utils/shop.js'
  import {
    preTNShopOrder,
    cancelTNShopOrder
  } from '@/api/pay.js'
  import {
    setTNShopAllowDeliverySubscribe
  } from '@/api/tn-shop-order.js'

  const util = require('@/utils/util')

  export default {
    name: 'TnShopSubmitOrder',
    data() {
      return {
        Custom: this.Custom,
        CustomBar: this.CustomBar,
        from: '',                               // 标记从哪里提交的订单
        shippingPicker: [
          '快递 包邮'
        ],                                      // 配送方式
        shippingPickerIndex: 0,                 // 所选配送方式的下标
        orderProductData: [],                   // 需要提交的商品展示数据
        orderData: {
          specs_data: [],
          address: {
            user_name: '',
            tel_number: '',
            province_name: '',
            city_name: '',
            county_name: '',
            detail_info: ''
          },
          notes: '',
          allow_pay_subscribe: 0,
          allow_submit_success_subscribe: 0,
          allow_pay_timeout_subscribe: 0
        },                                    // 订单提交到后台的数据
        isVirtualOrder: false,                // 标记是否为虚拟订单
        checkUserScopeFlag: false,            //用户是否已经授权
        showLogin: false,                     //打开登陆框
      }
    },
    computed: {
      orderSumPrice() {
        return this.orderProductData.reduce((total, item) => {
          return total + (parseFloat(item.price) * parseInt(item.count))
        }, 0.0)
      }
    },
    onLoad(options) {
      this.from = options.from || ''
      this._loadData()
    },
    methods: {
      // 用户选择收货地址
      chooseUserAddress() {
        uni.chooseAddress({
          success: (res) => {
            console.log(res);
            this.orderData.address = {
              user_name: res.userName,
              tel_number: res.telNumber,
              province_name: res.provinceName,
              city_name: res.cityName,
              county_name: res.countyName,
              detail_info: res.detailInfo
            }
          },
          fail: (err) => {
            // console.log(err);
            uni.showModal({
              showCancel: false,
              title: '错误信息',
              content: '获取收货地址失败，请重试'
            })
          }
        })
      },
      // 更改配送方式
      shippingChange(event) {
        // console.log(event);
      },

      // 提交订单
      submitOrder() {
        this._checkUserScope().then(async () => {
          
          if (this._checkSubmitDataIsExist()) {
            const allow_ids = await util.checkSubscribeSetting(['IwhmNHIdELTGvNTqlo4Tz1y-7ojU7GsZAkB0qVU34BY',
              'Ev6s1nV6j22jNtjgMIWKhnfsRX3UX6ofoC6geqQydMc', 'JJRcSBXljaR7aRuGBiyY1r8vhB_aUUmirxrkCsYNQRk'
            ])
            
            this.orderData.allow_submit_success_subscribe = allow_ids.indexOf('Ev6s1nV6j22jNtjgMIWKhnfsRX3UX6ofoC6geqQydMc') != -1 ? 1 : 0
            this.orderData.allow_pay_subscribe = allow_ids.indexOf('IwhmNHIdELTGvNTqlo4Tz1y-7ojU7GsZAkB0qVU34BY') != -1 ? 1 : 0
            this.orderData.allow_pay_timeout_subscribe = allow_ids.indexOf('JJRcSBXljaR7aRuGBiyY1r8vhB_aUUmirxrkCsYNQRk') != -1 ? 1 : 0
            
            // 获取预支付码
            preTNShopOrder(this.orderData).then((response) => {
              const { data } = response
              uni.requestPayment({
                provider: 'wxpay',
                timeStamp: data.timeStamp,
                nonceStr: data.nonceStr,
                package: data.package,
                signType: data.signType,
                paySign: data.paySign,
                success: (res) => {
                  this._clearShoppingCartSubmitProduct()
                  this._checkDeliverySubscribe(data.order_no, () => {
                    setTimeout(() => {
                      if(this.isVirtualOrder) {
                        uni.showModal({
                          showCancel:false,
                          title: "购买提示",
                          content: "当前购买的是服务商品，请购买后点击联系客服进行服务",
                          success: (res) => {
                            if(res.confirm) {
                              uni.redirectTo({
                                url: '/tn_shop/order_list/order_list'
                              })
                            }
                          }
                        })
                      } else {
                        uni.redirectTo({
                          url: '/tn_shop/order_list/order_list'
                        })
                      }
                    }, 1500)
                  })
                  uni.showToast({
                    title: '支付成功...',
                    icon: 'none'
                  })
                },
                fail: async (err) => {
                  this._clearShoppingCartSubmitProduct()
                  await cancelTNShopOrder({
                    order_no: data.order_no
                  })
                  uni.showToast({
                    title: '支付失败',
                    icon: 'none',
                    success: () => {
                      setTimeout(() => {
                        uni.redirectTo({
                          url: '/tn_shop/order_list/order_list'
                        })
                      }, 1500)
                    }
                  })
                }
              })
            }).catch((err) => {
              uni.showToast({
                icon: 'none',
                title: err.msg || '请求支付失败'
              })
            })
          }
        }).catch(() => {
          this.showLogin = true
        })
      },

      // 判断是跳转到首页还是上一页
      goBack() {
        if (this.from == 'share') {
          uni.navigateTo({
            url: '/pages/index/index'
          })
        } else {
          uni.navigateBack({
            delta: 1
          })
        }
      },

      //获取用户登陆状态
      getUserInfo() {
        if (res != null) {
          updateUserInfoToServer(res).then(() => {
            this.checkUserScopeFlag = true;
            util.showTips('登陆成功', '请继续执行上一步操作');
            this.closeLoginModal()
          }).catch(() => {
            util.showTips('授权提示', '获取授权失败')
            this.closeLoginModal()
          })
        } else {
          this.closeLoginModal()
        }
      },

      // 跳转到购物车
      navShoppingCart() {
        uni.navigateTo({
          url: '/tn_shop/shopping_cart/shopping_cart'
        })
      },


      // 加载数据
      _loadData() {
        this._getOrderProductData()
      },

      // 获取缓存中下单商品数据
      _getOrderProductData() {
        this.orderProductData = getSubmitOrderProductFromCache()
        if (this.orderProductData.length == 0) {
          uni.showModal({
            showCancel: false,
            title: '订单信息错误',
            content: '需要提交的订单商品数据为空，请重新下单',
            success: () => {
              uni.navigateBack({
                delta: 1
              })
            }
          })
          return
        }
        
        // 判断待提价的订单数组中是否包含服务订单，并且订单商品数量大于1
        this.isVirtualOrder = this.orderProductData.some((product) => {
          if (product.virtual_product == 1) {
            return true
          }
        })
        if (this.isVirtualOrder && this.orderProductData.length > 1) {
          uni.showModal({
            showCancel: false,
            title: '订单信息错误',
            content: '服务商品需要单独下单，请重新下单',
            success: () => {
              uni.navigateBack({
                delta: 1
              })
            }
          })
          return
        }

        // 添加数据到提交订单到信息数据中
        this.orderData.specs_data = []
        this.orderProductData.forEach((item) => {
          this.orderData.specs_data.push({
            product_id: item.product_id,
            specs_id: item.id,
            count: item.count
          })
        })
      },
      
      // 如果是从购物车跳转到下单页面，则清空购物车已下单的商品
      _clearShoppingCartSubmitProduct() {
        if (this.from == 'cart') {
          const shopping_cart_data = getShoppingCartDataFromCache()
          
          // 获取当前提交商品的id
          const product_ids = this.orderProductData.map((item) => {
            return item.id
          })
          // console.log(product_ids);
          
          // 去除当前被提交的商品数据
          const new_shopping_cart_data = shopping_cart_data.filter((item) => {
            return product_ids.indexOf(item.id) == -1
          })
          // console.log(new_shopping_cart_data);
          updateShoppingCartDataToCache(new_shopping_cart_data)
        }
        
        
        // 清空当前需要提交订单的商品缓存数据
        addSubmitOrderProductToCache([])
      },
      
      // 如果支付成功询问用户是否推送发货通知
      async _checkDeliverySubscribe(order_no, success_function) {
        const allow_ids = await util.checkSubscribeSetting(['4wDuEywMFodW26lQEMuMPQpOyPHLd7Ofs0eAonyyrY8'])
        
        if (allow_ids.indexOf('4wDuEywMFodW26lQEMuMPQpOyPHLd7Ofs0eAonyyrY8') != -1) {
          setTNShopAllowDeliverySubscribe({
            order_no,
            allow_delivery_subscribe: 1
          }).then(() => {
            if (success_function && typeof(success_function) === 'function') {
              success_function()
            }
          })
        } else {
          if (success_function && typeof(success_function) === 'function') {
            success_function()
          }
        }
      },

      // 检查必要的信息是否存在
      _checkSubmitDataIsExist() {
        const address = this.orderData.address
        const specs_data = this.orderData.specs_data
        if (specs_data.length == 0) {
          uni.showToast({
            icon: 'none',
            title: '请选择商品'
          })
          return false
        }

        if (address.user_name == '' ||
          address.tel_number == '' ||
          address.detail_info == ''
        ) {
          uni.showToast({
            icon: 'none',
            title: '请填写收货信息'
          })
          return false
        }

        // console.log(address, (/^1(3|4|5|7|8)\d{9}$/.test(address.tel_number)), (/^(\d{3,4}-)?\d{7,8}$/.test(address.tel_number)));
        if (!(/^(\d{3,4}-)?\d{7,8}$/.test(address.tel_number)) && !(/^1(3|4|5|7|8)\d{9}$/.test(address.tel_number))) {
          uni.showToast({
            icon: 'none',
            title: '联系方式有误，请重填'
          })
          return false
        }

        return true
      },

      // 检查当前用户的权限
      _checkUserScope() {
        return new Promise((resolve, reject) => {
          checkUserScope().then((res) => {
            this.checkUserScopeFlag = res
            resolve();
          }).catch((res) => {
            this.checkUserScopeFlag = res
            reject();
          });
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  .tn-shop-submit-order {
    background-color: #f1eef3;

    .address {
      .list {
        border-bottom: 0.5px solid #ECECEC;
      }

      .get-address {
        width: 100%;
      }
    }

    .order-product {
      .list {
        margin: 10px;

        .product-information {
          position: absolute;
          bottom: 0;
          width: 100%;
          background-color: transparent;
          padding: 0rpx 30rpx 10rpx 30rpx;

          .title {
            text-overflow: ellipsis;
          }

          .property {
            width: 100%;
            word-wrap: break-word;
            -webkit-line-break: after-white-space;
            background-color: rgba(125, 125, 125, 0.3);
            padding: 3px 8px;
            border-radius: 5px;
          }
        }
      }
    }

    .order-information {
      .list {
        border-bottom: 0.5px solid #ECECEC;
        padding: 0px;

        .cu-form-group {
          width: 100%;
        }
      }

      .shipping {}
    }
  }
</style>
